using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.MeetingRooms;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.MeetingRooms
{
    public class GetRoomDetailCommandHandler : IRequestHandler<GetRoomDetailCommand, APIResult<RoomDto>>
    {
        private readonly IBaseRepository<MeetingRoom> _mrRep;
        private readonly IMapper _mapper;
        private readonly ILogger<GetRoomDetailCommandHandler> _logger;

        public GetRoomDetailCommandHandler(
            IBaseRepository<MeetingRoom> mrRep,
            IMapper mapper,
            ILogger<GetRoomDetailCommandHandler> logger)
        {
            _mrRep = mrRep;
            _mapper = mapper ;
            _logger = logger ;
        }

        public async Task<APIResult<RoomDto>> Handle(GetRoomDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询会议室信息
                var room = await _mrRep.GetAll()
                    .FirstOrDefaultAsync(r => r.MeetingRoomId == request.MeetingRoomId && !r.IsDel);

                if (room == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.MeetingRoomId} 的会议室");
                    return new APIResult<RoomDto>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "未找到指定的会议室",
                        Data = null
                    };
                }

                // 转换为DTO
                var roomDto = _mapper.Map<RoomDto>(room);

                _logger.LogInformation($"成功获取会议室信息: ID {request.MeetingRoomId}");
                return new APIResult<RoomDto>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "获取会议室信息成功",
                    Data = roomDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取会议室信息失败: ID {request.MeetingRoomId}");
                return new APIResult<RoomDto>
                {
                    Code = StatusEnumCode.Fail,
                    Message = "获取会议室信息失败",
                    Data = null
                };
            }
        }
    }
} 